import * as React from 'react';
import { IState} from "./WriteArticle";
import '../../static/writeArticle.css';
import API from '../../API';
import ListFactory from "./lib/ListFactory";
import {connect} from 'react-redux';
import {IReducer} from "../../reducer";

export interface IAnthologyFromProps{
    createAnthologyNoDisplayAndRefreshWriteArticle:any,
    isCreateAnthologyDisplay:boolean,
    refreshWriteArticle:any,
    liLists:ListFactory
    componentRefreshReduce :any
}

class AnthologySubmit extends React.Component<IAnthologyFromProps>{
    state:IState;
    anthologyTitle:string = '';
    inputValue:string = '';

    setAnthologyTitle(e:any){
        this.anthologyTitle = this.inputValue = e.target.value;
        this.setState({});
    }

    clearInputValue(){
        this.inputValue = '';
    }

    componentDidMount(){
    }

    /**
     * 创建并上传新的文集到数据库,然后刷新文集列表
     * */
    async submit(anthologyTitle:string, e:Event){
        e.stopPropagation();
        this.clearInputValue();
        if(anthologyTitle==='')return ;
        await API.post.createAnthology({anthology:`${anthologyTitle}`,name:'coffeeCat'}).then((res)=>{
        });
        await this.getAnthology();
        const {refreshAndUpdateArticleList} = this.props.componentRefreshReduce;
        refreshAndUpdateArticleList();
        this.inputValue = '';
    }


    getAnthology (){
        const liLists = this.props.liLists;
        return API.post.getAnthology().then((res)=>{
            const {result} = res.data;
            liLists.againSetList(result);
            this.props.refreshWriteArticle();
        });
    };

    createAnthologyNoDisplay =()=>{
        this.setState({isCreateAnthologyDisplay:false});
    };

    render(){
        let isCreateAnthologyDisplay = this.props.isCreateAnthologyDisplay;
        if(isCreateAnthologyDisplay){
            return (
                <div>
                    <form/>
                    <input type="text"
                           onChange={this.setAnthologyTitle.bind(this)}
                           value={this.inputValue} placeholder="请输入文集名..."
                           className="anthologyTitle"/>
                    <button type="button"
                            className={"anthologySubmit"}
                            onClick={this.submit.bind(this,this.anthologyTitle)}>提交</button>
                    <button type="button"
                            onClick={this.props.createAnthologyNoDisplayAndRefreshWriteArticle}
                            className={"anthologyCancel"}>取消</button>
                </div>
            )
        }else{
            return null
        }
    }
}

export default connect((state:IReducer)=>{
        const {componentRefreshReduce} = state;
        return {componentRefreshReduce};
    },
    (dispatch)=>{return {dispatch}},
    undefined,
    {pure:false})(AnthologySubmit);

